package com.business_clean.ui.activity.attendance;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.lifecycle.Observer;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.business_clean.R;
import com.business_clean.app.App;
import com.business_clean.app.base.BaseActivity;
import com.business_clean.app.ext.CommonUtils;
import com.business_clean.app.ext.LoadingDialogExtKt;
import com.business_clean.app.uitl.ActivityForwardUtil;
import com.business_clean.app.uitl.DownLoadHelper;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.data.mode.BaseDownLoadEntity;
import com.business_clean.data.mode.attendance.FilterAttendanceData;
import com.business_clean.data.mode.attendance.MyAttendanceDetailEntity;
import com.business_clean.databinding.ActivityProjectAttendanceBinding;
import com.business_clean.ui.activity.address.AddressManagerActivity;
import com.business_clean.ui.activity.classes.ClassesMangerActivity;
import com.business_clean.ui.activity.depart.DepartActivity;
import com.business_clean.ui.activity.group.GroupManagerActivity;
import com.business_clean.ui.adapter.viewpager2.FragmentLazyPagerAdapter;
import com.business_clean.ui.fragment.attendance.DateAttendanceFragment;
import com.business_clean.ui.fragment.attendance.DateAttendanceMonthFragment;
import com.business_clean.ui.fragment.main.TodoFragment;
import com.business_clean.ui.fragment.todo.TodoItemFragment;
import com.business_clean.viewmodel.request.AttendanceViewModel;
import com.google.android.material.tabs.TabLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.idlefish.flutterboost.FlutterBoost;
import com.idlefish.flutterboost.FlutterBoostRouteOptions;
import com.lxj.xpopup.interfaces.OnSelectListener;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.functions.Consumer;
import me.hgj.mvvmhelper.base.BaseViewModel;
import me.hgj.mvvmhelper.ext.LogExtKt;
import rxhttp.wrapper.entity.Progress;
import rxhttp.wrapper.param.RxHttp;

public class ProjectAttendanceActivity extends BaseActivity<AttendanceViewModel, ActivityProjectAttendanceBinding> {


    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private ArrayList<String> stringList = new ArrayList<>();

    public static int position = 0; //上个界面传递过来的，默认是0

    public static boolean isToday;//记录要跳转到那个fragment

    private FilterAttendanceData filterAttendanceData;
    private FilterAttendanceData filterAttendanceDayData;


    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        ImmersionBar.with(this).titleBar(mDatabind.llTabbar)
                .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                .init();
        if (getIntent() != null && getIntent().getExtras() != null) {
            position = getIntent().getExtras().getInt("position");
            isToday = getIntent().getExtras().getBoolean("isDay");
        }

        if (filterAttendanceData == null) {
            filterAttendanceData = new FilterAttendanceData();
            filterAttendanceData.setProject_uuid(App.appViewModelInstance.getProjectInfo().getValue().getUuid());
            if (getIntent().getExtras().getString("date_month") != null) {
                filterAttendanceData.setSearch_month(getIntent().getExtras().getString("date_month"));
            } else {
                filterAttendanceData.setSearch_month(TimeUtils.millis2String(TimeUtils.getNowMills(), "yyyy-MM"));
            }
        }
        if (filterAttendanceDayData == null) {
            filterAttendanceDayData = new FilterAttendanceData();
            filterAttendanceDayData.setProject_uuid(App.appViewModelInstance.getProjectInfo().getValue().getUuid());
            if (getIntent().getExtras().getString("date") != null) {
                filterAttendanceDayData.setSearch_month(getIntent().getExtras().getString("date"));
            } else {
                filterAttendanceDayData.setSearch_month(TimeUtils.millis2String(TimeUtils.getNowMills(), "yyyy-MM"));
            }
        }
        DateAttendanceFragment attendanceFragment = new DateAttendanceFragment();
        attendanceFragment.setArguments(getIntent().getExtras());

        DateAttendanceMonthFragment attendanceMonthFragment = new DateAttendanceMonthFragment();
        attendanceMonthFragment.setArguments(getIntent().getExtras());
        stringList.add("日报");
        stringList.add("月报");

        mFragments.add(attendanceFragment);
        mFragments.add(attendanceMonthFragment);

        getMDatabind().viewpager.setOffscreenPageLimit(mFragments.size());
        getMDatabind().viewpager.setAdapter(new FragmentLazyPagerAdapter(getSupportFragmentManager(), mFragments, stringList));
        getMDatabind().viewpager.setCurrentItem(isToday ? 0 : 1, false);
        getMDatabind().tabLayout.setupWithViewPager(getMDatabind().viewpager);

    }

    @Override
    public void onBindViewClick() {
        getMDatabind().ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        getMDatabind().ivPort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                String[] strings = {"导出考勤统计报表", "小组管理", "班次管理", "打卡地点管理"};

                CommonUtils.showBottomListWith(ProjectAttendanceActivity.this, 20, "", strings, new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        switch (position) {
                            case 0:
                                XXPermissions.with(ProjectAttendanceActivity.this)
                                        .permission(Permission.WRITE_EXTERNAL_STORAGE)
                                        .request(new OnPermissionCallback() {
                                            @Override
                                            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                                                if (allGranted) {

                                                    HashMap<String, String> hashMap = new HashMap<>();
                                                    if (getMDatabind().viewpager.getCurrentItem() == 0) {
                                                        hashMap.put("project_uuid", "" + filterAttendanceDayData.getProject_uuid());
                                                        hashMap.put("group_uuid", "" + filterAttendanceDayData.getGroup_uuid());
                                                        if (!TextUtils.isEmpty(filterAttendanceDayData.getSearch_month()) && filterAttendanceDayData.getSearch_month().length() > 6) {
                                                            hashMap.put("search_month", "" + filterAttendanceDayData.getSearch_month().substring(0, 7));
                                                        }
                                                        hashMap.put("stat_status", "" + filterAttendanceDayData.getStat_status());
                                                    } else {
                                                        hashMap.put("project_uuid", "" + filterAttendanceData.getProject_uuid());
                                                        hashMap.put("group_uuid", "" + filterAttendanceData.getGroup_uuid());
                                                        hashMap.put("search_month", "" + filterAttendanceData.getSearch_month());
                                                        hashMap.put("stat_status", "" + filterAttendanceData.getStat_status());
                                                    }
                                                    hashMap.put("op_type", "month_attendance");
                                                    mViewModel.requestDownloadExcel(hashMap);
                                                }
                                            }
                                        });
                                break;
                            case 1://小组管理
                                ActivityForwardUtil.startActivity(GroupManagerActivity.class);
                                break;
                            case 2://班次管理
                                ActivityForwardUtil.startActivity(ClassesMangerActivity.class);
                                break;
                            case 3://打卡地点管理
                                ActivityForwardUtil.startActivity(AddressManagerActivity.class);
                                break;
                        }
                    }
                });
            }
        });
    }

    @Override
    public void initObserver() {
        //监听月报的操作按钮点击
        App.appViewModelInstance.getFilterAttendanceData().observe(this, new Observer<FilterAttendanceData>() {
            @Override
            public void onChanged(FilterAttendanceData data) {
                filterAttendanceData = data;
            }
        });
        //监听日报的操作按钮点击
        App.appViewModelInstance.getFilterAttendanceDayData().observe(this, new Observer<FilterAttendanceData>() {
            @Override
            public void onChanged(FilterAttendanceData data) {
                filterAttendanceDayData = data;
            }
        });
    }


    @Override
    public void onRequestSuccess() {
        mViewModel.getDownLoadEntity().observe(this, new Observer<BaseDownLoadEntity>() {
            @Override
            public void onChanged(BaseDownLoadEntity baseDownLoadEntity) {
                String fileName = App.appViewModelInstance.getUserInfo().getValue().getCompany().getCompany_name() + "_" +
                        App.appViewModelInstance.getProjectInfo().getValue().getProject_short_name()
                        + "_" + TimeUtils.date2String(TimeUtils.getNowDate(), "yyyy-MM-dd hh分mm秒");
                DownLoadHelper.downloadFile(ProjectAttendanceActivity.this, baseDownLoadEntity.getDownload_url(), null, fileName, true);
            }
        });
    }
}